package k8s_ui

import (
	"context"
	"encoding/json"
	"errors"
	"github.com/wonderivan/logger"
	appsv1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/intstr"
	"strconv"
	"time"
)

var DaemonSet daemonSet

type daemonSet struct{}

// 定义DaemonSetCreate结构体，用于创建daemonSet需要的参数属性的定义
type DaemonSetCreate struct {
	Name          string            `json:"name"`
	Namespace     string            `json:"namespace"`
	Image         string            `json:"image"`
	Label         map[string]string `json:"label"`
	Cpu           string            `json:"cpu"`
	Memory        string            `json:"memory"`
	ContainerPort int32             `json:"container_port"`
	HealthCheck   bool              `json:"health_check"`
	HealthPath    string            `json:"health_path"`
	Pool          string            `json:"pool"`
}

// 定义DeploysNp类型，用于返回namespace中daemonSet的数量
type DaemonSetNp struct {
	Namespace string `json:"namespace"`
	DaemonNum int    `json:"daemonSet_num"`
}

type DaemonSetsResp struct {
	Items []appsv1.DaemonSet `json:"items"`
	Total int                `json:"total"`
}

func (p *daemonSet) GetdaemonSets(filterName, namespace string, limit, page int) (daemonSetsResp *DaemonSetsResp, err error) {
	//获取DaemonSetList类型的daemonSet列表
	daemonSetList, err :=
		K8s.ClientSet.AppsV1().DaemonSets(namespace).List(context.TODO(),
			metav1.ListOptions{})
	if err != nil {
		logger.Error(errors.New("获取DaemonSet列表失败, " + err.Error()))
		return nil, errors.New("获取DaemonSet列表失败, " + err.Error())
	}

	//将DaemonSetList中的daemonSet列表(Items)，放进dataselector对象中，进行排序
	selectableData := &DataSelector{
		GenericDataList: p.toCells(daemonSetList.Items),
		DataSelect: &DataSelectQuery{
			Filter: &FilterQuery{Name: filterName},
			Paginate: &PaginateQuery{
				Limit: limit,
				Page:  page,
			},
		},
	}
	filtered := selectableData.Filter()
	total := len(filtered.GenericDataList)
	data := filtered.Sort().Paginate()
	//将[]DataCell类型的daemonSet列表转为appsv1.daemonset列表
	daemonSets := p.fromCells(data.GenericDataList)
	return &DaemonSetsResp{
		Items: daemonSets,
		Total: total,
	}, nil
}

// toCells方法用于将pod类型转成DataCell类型
func (*daemonSet) toCells(std []appsv1.DaemonSet) []DataCell {
	cells := make([]DataCell, len(std))
	for i := range std {
		//std[i]原生pod类型 -> podCell -> DataCell
		cells[i] = daemonsetCell(std[i])
	}
	return cells
}

// fromCells方法用于将DataCell类型转成pod类型
func (*daemonSet) fromCells(cells []DataCell) []appsv1.DaemonSet {
	daemonsets := make([]appsv1.DaemonSet, len(cells))
	for i := range cells {
		//cells[i] DataCell接口类型 -> podCell -> 原生pod类型
		daemonsets[i] = appsv1.DaemonSet(cells[i].(daemonsetCell))
	}
	return daemonsets
}

// 获取每个namespace的daemonSet数量
func (d *daemonSet) GetdaemonSetNumPerNp() (daemonSetNps []*DaemonSetNp, err error) {
	namespaceList, err := K8s.ClientSet.CoreV1().Namespaces().List(context.TODO(),
		metav1.ListOptions{})
	if err != nil {
		return nil, err
	}
	for _, namespace := range namespaceList.Items {
		daemonsetList, err :=
			K8s.ClientSet.AppsV1().DaemonSets(namespace.Name).List(context.TODO(),
				metav1.ListOptions{})
		if err != nil {
			return nil, err
		}
		daemonSetNp := &DaemonSetNp{
			Namespace: namespace.Name,
			DaemonNum: len(daemonsetList.Items),
		}
		daemonSetNps = append(daemonSetNps, daemonSetNp)
	}
	return daemonSetNps, nil
}

// 获取daemonSet详情
func (d *daemonSet) GetdaemonSetDetail(daemonSetName, namespace string) (daemonset *appsv1.DaemonSet, err error) {
	daemonset, err =
		K8s.ClientSet.AppsV1().DaemonSets(namespace).Get(context.TODO(), daemonSetName,
			metav1.GetOptions{})
	if err != nil {
		logger.Error(errors.New("获取daemonset详情失败, " + err.Error()))
		return nil, errors.New("获取daemonset详情失败, " + err.Error())
	}
	return daemonset, nil
}

// 创建daemonSet,接收DeployCreate对象
func (d *daemonSet) CreatedaemonSet(data *DaemonSetCreate) (err error) {
	//将data中的数据组装成appsv1.daemonSet对象
	daemonSet := &appsv1.DaemonSet{
		//ObjectMeta中定义资源名、命名空间以及标签
		ObjectMeta: metav1.ObjectMeta{
			Name:      data.Name,
			Namespace: data.Namespace,
			Labels:    data.Label,
		},
		//Spec中定义副本数、选择器、以及pod属性
		Spec: appsv1.DaemonSetSpec{
			//Replicas: &data.Replicas,
			Selector: &metav1.LabelSelector{
				MatchLabels: data.Label,
			},
			Template: corev1.PodTemplateSpec{
				//定义pod名和标签
				ObjectMeta: metav1.ObjectMeta{
					Name:   data.Name,
					Labels: data.Label,
				},
				//定义容器名、镜像和端口
				Spec: corev1.PodSpec{
					Containers: []corev1.Container{
						{
							Name:  data.Name,
							Image: data.Image,
							Ports: []corev1.ContainerPort{
								{
									Name:          "http",
									Protocol:      corev1.ProtocolTCP,
									ContainerPort: 80,
								},
							},
						},
					},
				},
			},
		},
		//Status定义资源的运行状态，这里由于是新建，传入空的appsv1.daemonSetStatus{}对象即可
		Status: appsv1.DaemonSetStatus{},
	}
	//判断是否打开健康检查功能，若打开，则定义ReadinessProbe和LivenessProbe
	if data.HealthCheck {
		//设置第一个容器的ReadinessProbe，因为我们pod中只有一个容器，所以直接使用index 0即可
		//若pod中有多个容器，则这里需要使用for循环去定义了
		daemonSet.Spec.Template.Spec.Containers[0].ReadinessProbe = &corev1.Probe{
			ProbeHandler: corev1.ProbeHandler{
				HTTPGet: &corev1.HTTPGetAction{
					Path: data.HealthPath,
					//intstr.IntOrString的作用是端口可以定义为整型，也可以定义为字符串
					//Type=0则表示表示该结构体实例内的数据为整型，转json时只使用IntVal的数据
					//Type=1则表示表示该结构体实例内的数据为字符串，转json时只使用StrVal的数据
					Port: intstr.IntOrString{
						Type:   0,
						IntVal: data.ContainerPort,
					},
				},
			},
			//初始化等待时间
			InitialDelaySeconds: 5,
			//超时时间
			TimeoutSeconds: 5,
			//执行间隔
			PeriodSeconds: 5,
		}
		daemonSet.Spec.Template.Spec.Containers[0].LivenessProbe = &corev1.Probe{
			ProbeHandler: corev1.ProbeHandler{
				HTTPGet: &corev1.HTTPGetAction{
					Path: data.HealthPath,
					Port: intstr.IntOrString{
						Type:   0,
						IntVal: data.ContainerPort,
					},
				},
			},
			InitialDelaySeconds: 15,
			TimeoutSeconds:      5,
			PeriodSeconds:       5,
		}
		//定义容器的limit和request资源
		daemonSet.Spec.Template.Spec.Containers[0].Resources.Limits =
			map[corev1.ResourceName]resource.Quantity{
				corev1.ResourceCPU:    resource.MustParse(data.Cpu),
				corev1.ResourceMemory: resource.MustParse(data.Memory),
			}
		daemonSet.Spec.Template.Spec.Containers[0].Resources.Requests =
			map[corev1.ResourceName]resource.Quantity{
				corev1.ResourceCPU:    resource.MustParse(data.Cpu),
				corev1.ResourceMemory: resource.MustParse(data.Memory),
			}
	}
	//调用sdk创建aemonSet
	_, err = K8s.ClientSet.AppsV1().DaemonSets(data.Namespace).Create(context.TODO(),
		daemonSet, metav1.CreateOptions{})
	if err != nil {
		logger.Error(errors.New("创建daemonSet失败, " + err.Error()))
		return errors.New("创建daemonSet失败, " + err.Error())
	}
	return nil
}

// 删除aemonSet
func (d *daemonSet) DeletedaemonSet(daemonsetName, namespace string) (err error) {
	err = K8s.ClientSet.AppsV1().DaemonSets(namespace).Delete(context.TODO(),
		daemonsetName, metav1.DeleteOptions{})
	if err != nil {
		logger.Error(errors.New("删除DdaemonSet失败, " + err.Error()))
		return errors.New("删除daemonSet失败, " + err.Error())
	}
	return nil
}

// 重启aemonSet
func (*daemonSet) RestartdaemonSet(DaemonSetName, namespace string) (err error) {
	//此功能等同于一下kubectl命令
	//kubectl daemonSet ${service} -p \
	//'{"spec":{"template":{"spec":{"containers":[{"name":"'"${service}"'","env":
	//[{"name":"RESTART_","value":"'$(date +%s)'"}]}]}}}}'

	patchData := map[string]interface{}{
		"spec": map[string]interface{}{
			"template": map[string]interface{}{
				"spec": map[string]interface{}{
					"containers": []map[string]interface{}{
						{"name": DaemonSetName,
							"env": []map[string]string{{
								"name":  "RESTART_",
								"value": strconv.FormatInt(time.Now().Unix(), 10),
							}},
						},
					},
				},
			},
		},
	}

	//把patchData序列化成字节
	patchBytes, err := json.Marshal(patchData)
	if err != nil {
		logger.Error("序列化失败," + err.Error())
		return errors.New("序列化失败," + err.Error())
	}
	//更新daemonSet
	_, err = K8s.ClientSet.AppsV1().DaemonSets(namespace).Patch(context.TODO(), DaemonSetName, "application/strategic-merge-patch+json", patchBytes, metav1.PatchOptions{})
	if err != nil {
		logger.Error("重启DaemonSet失败," + err.Error())
		return errors.New("重启DaemonSet失败," + err.Error())
	}

	return nil
}

// 更新daemonSet
func (d *daemonSet) UpdatedaemonSet(namespace, content string) (err error) {
	var daemonset = &appsv1.DaemonSet{}
	err = json.Unmarshal([]byte(content), daemonset)
	if err != nil {
		logger.Error(errors.New("反序列化失败, " + err.Error()))
		return errors.New("反序列化失败, " + err.Error())
	}
	_, err = K8s.ClientSet.AppsV1().DaemonSets(namespace).Update(context.TODO(),
		daemonset, metav1.UpdateOptions{})
	if err != nil {
		logger.Error(errors.New("更新daemonset失败, " + err.Error()))
		return errors.New("更新daemonset失败, " + err.Error())
	}
	return nil
}
